import React, {useEffect, useRef, useState} from 'react';
import ProTable, {ActionType} from '@ant-design/pro-table';
import {TableConfig, TableConfigColumn} from './data.d';
import {modulesUrl} from "@/assets/constant/modulesUrl";
import {get, listForSelect} from "@/assets/service/baseService";
import {formSetFieldsValue, handleSave, hooksSet, isBlank, jumpPage} from "@/assets/utils/utils";
import {getTableNameList} from "@/pages/report/SourceList/service";
// @ts-ignore
import {useRequest} from 'umi';
import {Button, Card, DatePicker, Form, Input, InputNumber, message, Select, Space, Switch} from "antd";
import {getColumnList} from './service';
import {PageContainer} from "@ant-design/pro-layout";
import {ProFormText} from "@ant-design/pro-form";
import {jsonArrayGetIndex} from "@/assets/utils/jsonArrayUtils";
import {breadcrumbItemRender} from "@/assets/components/tableList";
import {dictType} from "@/assets/constant/dictType";
import moment from "moment";
import {getDateString, getYesterday} from "@/assets/utils/dateUtils";
import {RangeValue} from "rc-picker/lib/interface";

const TableConfigForm: React.FC<{}> = (props) => {

  // @ts-ignore
  const id = props.match.params.id;
  const [form] = Form.useForm();
  const actionRef = useRef<ActionType>();

  /**
   * 查询类型字典列表
   * @type 字典列表
   */
  const [queryTypeDictList, setQueryTypeDictList] = useState();
  useRequest(() => listForSelect(modulesUrl.sysDict, {type:dictType.TABLE_CONFIG_COLUMN_QUERY_TYPE}), {
    onSuccess: (result, params) => {
      hooksSet(setQueryTypeDictList, result)
    }
  })

  /**
   * 编辑时，获取表配置
   */
  const [tableConfig, setTableConfig] = useState<TableConfig>()
  const getTableConfigRun = useRequest((id: string) => get(modulesUrl.reportTableConfig, id), {
    manual: true,
    onSuccess: (result: TableConfig) => {
      hooksSet(setTableConfig, result)
      // 获取已选中的数据源的数据表列表
      getTableNameListRun(result.sourceId, undefined)
      // 获取已选中的数据表的数据字段列表
      getTableColumnListRun(result)
      // 属性回显
      formSetFieldsValue(form, result)
    }
  }).run
  /**
   * 获取数据源select列表
   */
  const [sourceSelectList, setSourceSelectList] = useState([])
  useRequest(() => listForSelect(modulesUrl.reportSource), {
    onSuccess: (result:any) => {
      hooksSet(setSourceSelectList, result);
    }
  })
  /**
   * 根据数据源，获取数据表列表
   */
  const [tableNameList, setTableNameList] = useState([]);
  const getTableNameListRun = useRequest((sourceId?: string, _?: any) => getTableNameList(sourceId), {
    manual: true,
    onSuccess: (result:any, params:any) => {
      if (result) {
        // 制作selectList
        let tableNameSelectList: any[] = []
        result.forEach((tableName: string) => tableNameSelectList.push({label: tableName, value: tableName}))
        hooksSet(setTableNameList, tableNameSelectList);
      }
      // @ts-ignore 关闭弹框
      params[1] && params[1]()
    }
  }).run
  /**
   * 根据数据表，获取字段列表
   */
  const [tableColumnList, setTableColumnList] = useState<TableConfigColumn[]>([]);
  const getTableColumnListRun = useRequest((tableConfig?: TableConfig) => getColumnList(tableConfig), {
    manual: true,
    onSuccess: (result:any, params:any) => {
      hooksSet(setTableColumnList, result, () => actionRef.current?.reload());
    }
  }).run

  /**
   * 启动加载
   */
  useEffect(() => {
    // 回显
    if (id !== "0") {
      getTableConfigRun(id);
    }
  }, []);

  return (
    <PageContainer
      title={(id ? "编辑" : "新建") + "表配置"}
      header={{
        breadcrumb: {
          routes: [
            {
              path: '/report/tableConfig',
              breadcrumbName: '表配置管理',
            },
            {
              path: '',
              breadcrumbName: (id ? "编辑" : "新建") + "表配置",
            }
          ],
          itemRender: breadcrumbItemRender
        }
      }}
    >
      <Card bordered={false} title={"数据表信息"}>
        <Form
          layout={"vertical"}
          form={form}
          preserve={false}
        >
          <ProFormText key="name" name="name" label="名称" placeholder="请输入名称"
                       rules={[{required: true, message: '名称为必填项',}]}/>
          <Form.Item key={"sourceId"} name={"sourceId"} label={"数据源"} rules={[{required: true, message: '数据源为必选项',}]}>
            <Select showSearch placeholder={"请选择数据源"} optionFilterProp={"label"} options={sourceSelectList}
                    onSelect={(value: string) => getTableNameListRun(value, message.loading('正在加载数据表'))}/>
          </Form.Item>
          <Form.Item key={"tableName"} name={"tableName"} label={"数据表"} rules={[{required: true, message: '数据表为必选项',}]}>
            <Select showSearch placeholder={"请选择数据表"} optionFilterProp={"label"} options={tableNameList}
                    onSelect={(value: string) => {
                      // value与当前tableName不相等，说明是新的
                      getTableColumnListRun(value === tableConfig?.tableName ? tableConfig : {
                        tableName: value,
                        sourceId: form.getFieldValue("sourceId")
                      })
                    }}/>
          </Form.Item>
          <Form.Item
            label="字段配置"
            name="dataSource"
            required
          >
            <ProTable
              rowKey="id"
              pagination={false}
              search={false}
              toolBarRender={false}
              actionRef={actionRef}
              columns={[
                {
                  title: '字段名称',
                  dataIndex: 'columnName',
                },
                {
                  title: '中文名称',
                  dataIndex: 'comment',
                  renderText: (text, record:TableConfigColumn) => (
                    <Input defaultValue={text} placeholder={"请输入中文名称"} onChange={(e) => {
                      let index = jsonArrayGetIndex(tableColumnList, "id", record.id);
                      if (index != undefined && index > -1) {
                        tableColumnList[index] = Object.assign({}, tableColumnList[index], {comment: e.target.value})
                      }
                    }}/>
                  )
                },
                {
                  title: '显示类型',
                  dataIndex: 'showType',
                  renderText: (text, record:TableConfigColumn) => (
                    <Select defaultValue={text} options={[
                      {label:'字符串或数字', value:"1"},
                      {label:'百分比', value:"2"},
                      {label:'日期', value:"3"},
                    ]} onSelect={(value: string) => {
                      let index = jsonArrayGetIndex(tableColumnList, "id", record.id);
                      if (index != undefined && index > -1) {
                        tableColumnList[index] = Object.assign({}, tableColumnList[index], {showType: value})
                      }
                    }}/>
                  )
                },
                {
                  title: '排序',
                  dataIndex: 'sort',
                  width:150,
                  renderText: (text, record:TableConfigColumn) => (
                    <InputNumber style={{width:"100%"}} defaultValue={text} placeholder={"请输入排序"} onChange={(value) => {
                      let index = jsonArrayGetIndex(tableColumnList, "id", record.id);
                      if (index != undefined && index > -1) {
                        tableColumnList[index] = Object.assign({}, tableColumnList[index], {sort:value})
                      }
                    }}/>
                  )
                },
                {
                  title: '是否展示',
                  dataIndex: 'isShow',
                  width:100,
                  renderText: (text, record:TableConfigColumn) => (
                    <Switch defaultChecked={text === "1"} onChange={(checked:boolean) => {
                      let index = jsonArrayGetIndex(tableColumnList, "id", record.id);
                      if (index != undefined && index > -1) {
                        tableColumnList[index] = Object.assign({}, tableColumnList[index], {isShow: checked? "1" : "0"})
                      }
                    }}/>
                  )
                },
                {
                  title: '是否查询',
                  dataIndex: 'isQuery',
                  width:100,
                  renderText: (text, record:TableConfigColumn) => (
                    <Switch defaultChecked={text === "1"} onChange={(checked:boolean) => {
                      let index = jsonArrayGetIndex(tableColumnList, "id", record.id);
                      if (index != undefined && index > -1) {
                        tableColumnList[index] = Object.assign({}, tableColumnList[index], {isQuery: checked? "1" : "0"})
                      }
                    }}/>
                  )
                },
                {
                  title: '查询方式',
                  dataIndex: 'queryType',
                  renderText: (text, record:TableConfigColumn) => (
                    <Select defaultValue={text} options={queryTypeDictList} onSelect={(value: string) => {
                      let index = jsonArrayGetIndex(tableColumnList, "id", record.id);
                      if (index != undefined && index > -1) {
                        tableColumnList[index] = Object.assign({}, tableColumnList[index], {queryType: value})
                      }
                    }}/>
                  )
                },
                {
                  title: '默认值',
                  dataIndex: 'queryInitialValue',
                  renderText: (text, record:TableConfigColumn) => {
                    let index = jsonArrayGetIndex(tableColumnList, "id", record.id) || "";
                    let result;
                    // 根据queryType不同，显示不同类型的框
                    if(record.queryType === "3" || record.queryType === "4"){
                      // 注入初始值
                      if(isBlank(record.queryInitialValue)){
                        tableColumnList[index] = Object.assign({}, tableColumnList[index], {queryInitialValue: getYesterday("yyyyMMdd") + "," + getYesterday("yyyyMMdd")})
                      }
                      // 为3或4，显示时间区间
                      result = <DatePicker.RangePicker
                        style={{width:"100%"}}
                        format={record.queryType === "3" ? "YYYY-MM-DD HH:mm:ss" : "YYYYMMDD"}
                        disabledDate={(currentDate) => currentDate && currentDate >= moment(getDateString("yyyyMMdd"), 'YYYYMMDD')}
                        defaultValue={[
                          moment(isBlank(record.queryInitialValue) ? getYesterday("yyyyMMdd") : record.queryInitialValue?.split(",")[0]),
                          moment(isBlank(record.queryInitialValue) ? getYesterday("yyyyMMdd") : record.queryInitialValue?.split(",")[1])
                        ]}
                        onChange={(values: RangeValue<any>, formatString: [string, string])=>{
                          tableColumnList[index] = Object.assign({}, tableColumnList[index], {queryInitialValue: formatString.join(",")})
                        }}
                      />
                    }else {
                      result = <Input defaultValue={text} placeholder={"请输入默认值"} onChange={(e) => {
                        if (index != undefined && index > -1) {
                          tableColumnList[index] = Object.assign({}, tableColumnList[index], {queryInitialValue: e.target.value})
                        }
                      }}/>
                    }
                    return result;
                  }
                }
              ]}
              request={async () => ({
                data: tableColumnList,
                total: 3,
                success: true,
              })}
            />
          </Form.Item>
          <Form.Item style={{textAlign: "right"}}>
            <Space>
              <Button onClick={() => jumpPage('/report/tableConfig')}>
                取消
              </Button>
              <Button type="primary" onClick={() => {
                // 去掉columnList的id，后台重新插入
                let columnList: TableConfigColumn[] = [];
                tableColumnList.forEach((initTableColumn: TableConfigColumn) => {
                  columnList.push(Object.assign({}, initTableColumn, {id: null}))
                })
                // 保存
                handleSave(form, modulesUrl.reportTableConfig, {"columnList": columnList}, () => {
                  jumpPage('/report/tableConfig')
                })
              }}>
                确定
              </Button>
            </Space>
          </Form.Item>
          <Form.Item initialValue={id !== "0" ? id : undefined} key="id" name="id"
                     className={"formItemHidden"}></Form.Item>
        </Form>
      </Card>
    </PageContainer>
  );
};

export default TableConfigForm;
